import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:ls_work/net/response/use_request/new_goods_list_data.dart';
import 'package:ls_work/net/response/use_request/use_request_record_detail_data.dart';
import 'package:ls_work/ui/use_request/new_choose_goods_page.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/viewmodel/use_request/add_use_request_view_model.dart';
import 'package:ls_work/viewmodel/use_request/new_choose_goods_view_model.dart';
import 'package:ls_work/widgets/requir_text_view.dart';

import '../../message/message_config.dart';
import '../../model/office_model.dart';
import '../../model/use_request/use_request_model.dart';
import '../../net/post_request.dart';
import '../../net/response/office_list_tree_data.dart';
import '../../net/response/response_data.dart';
import '../../net/response/use_request/goods_request_list_data.dart';
import '../../net/response/user_info_data.dart';
import '../../res/colors.dart';
import '../../res/gaps.dart';
import '../../ui/select_employee_page.dart';
import '../../ui/use_request/choose_goods_page.dart';
import '../../ui/use_request/office_list_page.dart';
import '../../widgets/bottom_input_widget.dart';
import '../../widgets/title_value_widget.dart';
import '../new_yyt_view_model.dart';

class NewAddUseRequestViewModel extends BaseViewModel {
  num? recordId;

  NewAddUseRequestViewModel(BuildContext context, {this.recordId})
      : super(context);

  UserInfoData? get userInfo => NewYytViewModel.userInfo;
  var officeModel = OfficeModel();
  var useRequestModel = UseRequestModel();

  var officeName = "";
  var officeId = "";

  var userName = "";
  var userId = "";

  var officePatentId = "";
  var oddNumbers = "";
  var canAudite = true;
  var selectList = <NewGoodsListData>[];
  dynamic approveType = 0;
  dynamic approveTypeName = '常规审批';
  dynamic status;
  String remark = "";
  String useTo = "";

  var useTypeList = [
    PickerDataWithIdModel(pickName: '常规入库物资', pickId: '0'),
    PickerDataWithIdModel(pickName: '捐赠入库物资', pickId: '1'),
  ];

  PickerDataWithIdModel? useType;

  @override
  void onCreated() {
    super.onCreated();
    useType = useTypeList.first;
    if (recordId != null) {
      getDetailData();
    } else {
      if (userInfo == null) {
        getUserInfo();
      } else {
        initUser();
      }
    }
  }

  void initUser() {
    officeName = userInfo?.officeName ?? "";
    officeId = userInfo?.officeId ?? "";
    userName = userInfo?.name ?? "";
    userId = userInfo?.id.toString() ?? "";
    getOfficePatent();
    notifyListeners();
  }

  Future<void> getUserInfo() async {
    showLoadingDialog();
    try {
      var data = await PostRequest.userInfo();
      hideDialog();
      var bean = ResponseBean.fromJson(data);
      if ("0" == bean.code) {
        var info = UserInfoData.fromJson(bean.data);
        NewYytViewModel.userInfo = info;
        initUser();
        notifyListeners();
      }
    } catch (e) {
      hideDialog();
    }
  }

  void selectUseType() {
    DataPickerView(context, useTypeList, onSubmitListener: (p1, p2, p3) {
      var item = useTypeList[p1];
      if (useType != item) {
        useType = item;
        selectList.clear();
      }
      notifyListeners();
    }).show();
  }

  Future<void> getDetailData() async {
    showLoadingState();
    try {
      var detail = await useRequestModel.requestDetail(recordId.toString());
      userName = detail.applyPerson ?? "";
      userId = detail.applyPersonId.toString();
      officeId = detail.officeId.toString();
      officeName = detail.office ?? "";
      selectList = (detail.logisticsMaterialApplicationDetailBeans ?? [])
          .map((e) => e.toNewGoods(officeId))
          .toList();
      oddNumbers = detail.applicationNo ?? "";
      canAudite = detail.canAudite ?? false;
      approveTypeName = detail.bpmTypeName;
      approveType = detail.bpmType;
      status = detail.status;
      useTo = detail.useTo ?? "";
      var list = useTypeList
          .where((element) => detail.useRange.toString() == element.pickId);
      if (list.isNotEmpty) {
        useType = list.first;
      }
      showContent();
    } catch (e) {
      showErrorState(NetErrorUtils.getNetError(e));
    }
  }

  void selectEmployee() {
    Go().push(SelectEmployeePage(
      onSelectListener: (employee) {
        Go().pop();
        userId = employee.id ?? "";
        userName = employee.name ?? "";
        notifyListeners();
      },
      officeId: officeId,
    ));
  }

  Future<void> getOfficePatent() async {
    if (officeId.isNullOrEmpty()) {
      return;
    }
    var parentData = await officeModel.infoData(officeId);
    if (parentData != null) {
      officePatentId = parentData.rootId.toString();
    }
  }

  Future<void> addRequestClick() async {
    NewGoodsListData? good = await Go().push(NewChooseGoodsPage());
    if (good != null) {
      if (!selectList.contains(good)) {
        good.selectNumber = 1;
        selectList.add(good);
        getApproveType();
        notifyListeners();
      }
    }
  }

  Map<String, dynamic>? getApproveType() {
    if (selectList.isNotEmpty) {
      var guding = false;
      var juanzeng = false;
      var putong = false;

      for (var item in selectList) {
        if (item.assetType.toString() == '1') {
          guding = true;
        }

        if (item.donate.toString() == "1") {
          juanzeng = true;
        }

        if (item.assetType.toString() != '1' && item.donate.toString() != '1') {
          putong = true;
        }
      }
      if ((guding || juanzeng) && !putong) {
        approveType = 1;
        approveTypeName = "固定资产审批";
      } else if ((guding || juanzeng) && putong) {
        approveType = 2;
        approveTypeName = "混合审批";
      } else {
        approveType = 0;
        approveTypeName = "常规审批";
      }
    } else {
      approveType = '';
      approveTypeName = "";
    }
    // var list =  selectList.map((e) => e.assetType).toList();
    // var list = <String>[];
    // for (var item in selectList) {
    //   // if (!list.contains(item.assetTypeName)) {
    //   //   list.add(item.assetTypeName);
    //   // }
    // }
    // if (list.length >= 2) {
    //   approveType = 2;
    //   approveTypeName = "混合审批";
    // }
    // if (list.length == 1) {
    //   if (list[0] == "固定资产") {
    //     approveType = 1;
    //     approveTypeName = "固定资产审批";
    //   }
    //
    //   if (list[0] == '消耗品' || list[0] == '低耗品') {
    //     approveType = 0;
    //     approveTypeName = "常规审批";
    //   }
    // }
  }

  Widget contentView() {
    var canChange = (status == null || status == 3);
    return Column(
      children: [
        SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TitleValueWidget(
                "申请部门",
                text: officeName,
                showArrow: canChange,
                isRequired: true,
              ).onTap(() async {
                if (!canChange) {
                  return;
                }
                await selectDepartment();
              }),
              Gaps.dividerLine,
              TitleValueWidget(
                "申请人",
                text: userName,
                showArrow: canChange,
                isRequired: true,
              ).onTap(() {
                if (!canChange) {
                  return;
                }
                selectEmployee();
              }),

              Gaps.dividerLine,
              // TitleValueWidget(
              //   "入库类型",
              //   text: useType?.pickName??"",
              //   showArrow: canChange,
              // ).onTap(() {
              //   if(!canChange){
              //     return;
              //   }
              //   selectUseType();
              // }),
              // Gaps.dividerLine,
              ...[
                SizedBox(
                  height: 12,
                ),
                RequireTextView('使用用途')
                    .addToContainer(margin: EdgeInsets.only(left: 16)),
                SizedBox(
                  height: 12,
                ),
                CommonInput(
                  isDense: true,
                  padding: EdgeInsets.zero,
                  border: InputBorder.none,
                  hintText: '请输入使用用途',
                  minLines: 4,
                  maxLines: 5,
                  text: useTo,
                  onChanged: (str) {
                    useTo = str;
                  },
                  keyboardType: CommonInputType.multiline,
                ).addToContainer(
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                    margin: EdgeInsets.symmetric(horizontal: 16),
                    decoration: BoxDecoration(
                        color: Colours.bg_color, borderRadius: 4.borderRadius)),
                SizedBox(
                  height: 12,
                ),
              ],
              Gaps.dividerLine,
              TitleValueWidget(
                "申请物资",
                rightWeight: (status == null || status == 3)
                    ? TextButton(
                        onPressed: () {
                          addRequestClick();
                        },
                        child: Text(
                          "新增物资",
                          style: TextStyle(color: Colors.white),
                        ),
                        style: ButtonStyle(
                            backgroundColor:
                                WidgetStateProperty.all(Colors.blue)),
                      )
                    : Container(),
                hint: "",
                padding: EdgeInsets.symmetric(horizontal: 16),
              ),
              if (selectList.isNotEmpty) ...[
                Row(
                  children: [
                    CommonText('物资名称').setWeight(1),
                    CommonText('物资类型').setWeight(1),
                    CommonText('单位').setWeight(1),
                    CommonText('申请数量').setWeight(1),
                  ],
                ).addToContainer(
                    margin: EdgeInsets.symmetric(horizontal: 16, vertical: 15)),
                DashLine(
                  axis: Axis.horizontal,
                  dashedWidth: 4,
                  count: 40,
                  dashedHeight: 1,
                  color: Colors.grey,
                ).addToContainer(margin: EdgeInsets.symmetric(horizontal: 16)),
                Column(
                  children: selectList.map((e) {
                    return Slidable(
                      child: Row(
                        children: [
                          CommonText(e.materialName).setWeight(1),
                          CommonText(e.materialTypeName ?? "").setWeight(1),
                          CommonText(e.unit ?? "").setWeight(1),
                          Row(
                            children: [
                              if (canChange)
                                Icon(
                                  Icons.remove_circle_outline,
                                  color: Colors.blue,
                                ).onTap(() {
                                  if (e.selectNumber == 1) {
                                    selectList.remove(e);
                                  } else {
                                    e.selectNumber--;
                                  }
                                  notifyListeners();
                                }),
                              CommonText('${e.selectNumber.d}',
                                      textAlign: TextAlign.center)
                                  .onTap(() {
                                showBottomInput(context,
                                    title: "申请数量",
                                    content: e.selectNumber.d.toString(),
                                    keyboard: CommonInputType.numberAndDecimal,
                                    onSubmit: (str) {
                                  var number = num.parse(str);
                                  if (e.inventoryQuantity != null &&
                                      number > (e.inventoryQuantity ?? 0)) {
                                    showToast("不可超过库存数量");
                                  } else {
                                    e.selectNumber = num.parse(str);
                                    notifyListeners();
                                  }
                                });
                              }).setWeight(1),
                              if (canChange)
                                Icon(
                                  Icons.add_circle_outline,
                                  color: Colors.blue,
                                ).onTap(() {
                                  if (e.inventoryQuantity != null &&
                                      e.selectNumber >=
                                          (e.inventoryQuantity ?? 0)) {
                                    showToast("不可超过库存数量");
                                  } else {
                                    e.selectNumber++;
                                    notifyListeners();
                                  }
                                }),
                            ],
                          ).setWeight(1),
                        ],
                      ).addToContainer(
                          margin: EdgeInsets.symmetric(
                              horizontal: 16, vertical: 15)),
                      endActionPane: canChange
                          ? ActionPane(
                              motion: const StretchMotion(),
                              children: [
                                SlidableAction(
                                  onPressed: (context) {
                                    selectList.remove(e);
                                    notifyListeners();
                                  },
                                  label: "删除",
                                  spacing: 2,
                                  backgroundColor: Colors.red,
                                  flex: 1,
                                )
                              ],
                            )
                          : null,
                    );
                  }).toList(),
                ),
              ],
            ],
          ),
        ).setWeight(1),
        (status == null || status == 3)
            ? Row(
                children: [
                  Container(
                    width: 16,
                  ),
                  TextButton(
                    onPressed: () {
                      finish();
                    },
                    child: CommonText("取消", textColor: Colors.blue),
                    style: ButtonStyle(
                        shape: WidgetStateProperty.all(RoundedRectangleBorder(
                            borderRadius: 4.borderRadius,
                            side: BorderSide(color: Colors.blue, width: 1)))),
                  ).setWeight(1),
                  if (selectList.isNotEmpty) ...[
                    Container(
                      width: 12,
                    ),
                    TextButton(
                      onPressed: () {
                        submitRequest(0);
                      },
                      child: CommonText("保存草稿", textColor: Colors.white),
                      style: ButtonStyle(
                          backgroundColor:
                              WidgetStateProperty.all(Colours.app_main),
                          shape: WidgetStateProperty.all(
                              RoundedRectangleBorder(
                                  borderRadius: 4.borderRadius))),
                    ).setWeight(1),
                  ],
                  if (selectList.isNotEmpty) ...[
                    Container(
                      width: 12,
                    ),
                    TextButton(
                      onPressed: () {
                        submitRequest(1);
                      },
                      child: CommonText("提交审批", textColor: Colors.white),
                      style: ButtonStyle(
                          backgroundColor:
                              WidgetStateProperty.all(Colors.blue),
                          shape: WidgetStateProperty.all(
                              RoundedRectangleBorder(
                                  borderRadius: 4.borderRadius))),
                    ).setWeight(1),
                  ],
                  Container(
                    width: 16,
                  ),
                ],
              )
            : -1 == status
                ? Row(
                    children: [
                      Container(
                        width: 16,
                      ),
                      TextButton(
                        onPressed: () {
                          showApplyDialog(
                              context: context,
                              onSubmit: () {
                                deleteRequest();
                              },
                              message: "确定要撤销审批吗？");
                        },
                        child: CommonText('撤销审批', textColor: Colors.white),
                        style: ButtonStyle(
                            backgroundColor:
                                WidgetStateProperty.all(Colors.blue)),
                      )
                    ],
                  )
                : Container(),
        Container(
          height: 15,
        )
      ],
    );
  }

  Future<void> selectDepartment() async {
    OfficeListTreeData data = await Go().push(OfficeListPage());
    // DepartmentListData data = await Go().push(DepartmentListPage());
    if (data != null) {
      officeName = data.officeName ?? "";
      officeId = data.id.toString();
      userName = "";
      userId = "";
      getOfficePatent();
      notifyListeners();
    }
  }

  ///提交
  ///[type] 0保存 1提交
  Future<void> submitRequest(dynamic type) async {
    if(officeName.isNullOrEmpty()){
      showToast("请选择申请部门");
      return;
    }
    if(userName.isNullOrEmpty()){
      showToast("请选择申请人");
      return;
    }
    if (useTo.isNullOrEmpty()) {
      showToast("请输入使用用途");
      return;
    }
    if (selectList.isEmpty) {
      showToast("请选择要申请的物资");
      return;
    }
    showLoadingDialog(msg: '提交中...');
    try {
      var result = await useRequestModel.addRequest(
        officeId: officePatentId,
        officeChildrenId: officeId,
        applyPersonId: userId,
        logisticsMaterialApplicationDetailBeans:
            selectList.map((e) => e.toSubmitInfo(officePatentId)).toList(),
        saveOrSubmit: type,
        bpmType: approveType,
        bpmTypeName: approveTypeName,
        person: userName,
        oddNumbers: oddNumbers,
        remark: remark,
        useTo: useTo,
        canAudite: canAudite,
        id: recordId,
        // useRange: useType.pickId,
        // useRangeName: useType.name
      );
      await Future.delayed(Duration(milliseconds: 1000));
      hideDialog();
      showToast("提交成功");
      sendMessage(SendMessageEvent(MessageConfig.ADD_REQUEST_SUCCESS));

      finish();
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  ///取消申请
  Future<void> deleteRequest() async {
    showLoadingDialog();
    try {
      await useRequestModel.deleteRequest(recordId);
      await Future.delayed(Duration(milliseconds: 1000));
      hideDialog();
      showToast("提交成功");
      sendMessage(SendMessageEvent(MessageConfig.ADD_REQUEST_SUCCESS));
      finish();
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }
}
